<?php

declare(strict_types=1);

namespace App\Model;

use App\Model\Stat\StatDailyHostInfo;
use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 * 主播信息
 */
class HostInfo extends Model
{
    protected $table = 'host_info';
    protected $fillable = ['user_id', 'host_time', 'voice_answer_time', 'video_answer_time', 'voice_answer_num', 'video_answer_num', 'income_total', 'income_gift', 'income_msg', 'income_voice', 'income_video', 'income_sysgift'];

    /**
     * 初始化当前主播信息
     */
    static function initHostInfo()
    {
        $validOffTime = date('Y-m-d H:i:s', time() - 3600 * 2);
        //更新三小时内活跃的主播
        $where = [
            ['status', User::STATUS_OK],
            ['gender', 0],
            ['role', UserProfile::ROLE_HOST],
            ['user_profile.updated_at', '>', $validOffTime]
        ];
        $hosts = Db::table('user_profile')->join('user', function ($join) {
            $join->on('user.id', '=', 'user_profile.user_id');
        })->where($where)->pluck('host_time', 'user_id')->toArray();
        foreach ($hosts as $hostId => $hostTime) {
            log_info(__METHOD__ . "==HostId:{$hostId}==HostTime:{$hostTime}");
            //总信息
            self::updateRecord($hostId, $hostTime);
        }
        return;
    }

    /**
     * 新增主播数据
     */
    static function updateRecord($userId = 0, $hostTime = 0)
    {
        $start = '2021-09-01';
        $end = '';
        return self::updateOrCreate(['user_id' => $userId], [
            'user_id' => $userId,
            'host_time' => $hostTime,
            'voice_answer_time' => VoiceCall::getCallNum('total_call_minutes', '', '', 0, 0, $userId),
            'video_answer_time' => VideoCall::getCallNum('total_call_minutes', '', '', 0, 0, $userId),
            'voice_answer_num' => VoiceCall::getCallNum('success_num', '', '', 0, 0, $userId),
            'video_answer_num' => VideoCall::getCallNum('success_num', '', '', 0, 0, $userId),
            'income_total' => CoinLog::getTotalIncome([$userId], $start, $end),
            'income_gift' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_GET_GIFT),
            'income_msg' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_SEND_PRIVATE_MSG_IN),
            'income_voice' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::VOICE_CALL_INCOME),
            'income_video' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::VIDEO_CALL_INCOME),
            'income_sysgift' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_GET_SYSGIFT),
            'income_video_default' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_VIDEOCALL_IN),
            'income_video_match' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_QUICK_VIDEO_IN),
            'income_video_invite' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_INVITE_VIDEO),
            'income_video_discount' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_DISCOUNT_VIDEO_CALL_IN),
            'income_video_daily_free' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_DAILY_FREE),
        ]);
    }

    /**
     * 每日主播信息
     */
    static function initDailyInfo($day = 1)
    {
        $start = date('Y-m-d', strtotime("-{$day} day"));
        $day--;
        $end = date('Y-m-d', strtotime("-{$day} day"));
        $where = [
            ['status', User::STATUS_OK],
            ['gender', 0],
            ['role', UserProfile::ROLE_HOST],
            ['user_profile.updated_at', '>', $start]
        ];
        $hostIds = Db::table('user_profile')->join('user', function ($join) {
            $join->on('user.id', '=', 'user_profile.user_id');
        })->where($where)->orderBy('user_id', 'desc')->pluck('user_id')->toArray();
        //在线信息
        $onlineInfo = UserActLog::onlineDuration($hostIds, $start, $end);
        log_info(__METHOD__ . "=={$start}==UpdateCount:" . count($hostIds) . "==OnlineCount:" . count($onlineInfo));
        foreach ($hostIds as $hostId) {
            //每日信息
            self::updateDailyRecord($hostId, $start, $end, $onlineInfo);
        }
        return;
    }

    /**
     * 新增主播数据
        $table->integer('online_time')->default(0)->comment('在线时长');
        $table->integer('video_answer_time')->default(0)->comment('视频接听时长');
        $table->integer('video_answer_num')->default(0)->comment('视频接听数');
        $table->double('success_rate', 3, 1)->default(0)->comment('成功接通率');
        $table->integer('video_call_num')->default(0)->comment('主动拨打次数');
        $table->integer('video_match_num')->default(0)->comment('主动速配次数');
        $table->double('msg_back_rate', 3, 1)->default(0)->comment('私信回复率');
        $table->integer('super_chat_num')->default(0)->comment('主动搭讪人数');
        $table->unsignedSmallInteger('receive_num')->default(0)->comment('接收名义礼物数量');
        $table->unsignedSmallInteger('receive_user_num')->default(0)->comment('接收名义礼物用户数量');
        $table->unsignedSmallInteger('msg_back_num')->default(0)->comment('回复的用户数');
     */
    static function updateDailyRecord($userId = 0, $start = '', $end = '', $onlineInfo = [])
    {
        if (!$userId || !$start) return;
        //名义礼物赠送人数
        $senderNum = GiftLog::checkSenderNum(
            $userId,
            $start,
            $end,
            [GiftLog::FROM_SUPER_CHAT, GiftLog::FROM_SYS_ONLINE]
        );
        //名义礼物赠送个数
        $sendGiftNum = GiftLog::checkSenderNum(
            $userId,
            $start,
            $end,
            [GiftLog::FROM_SUPER_CHAT, GiftLog::FROM_SYS_ONLINE],
            -1,
            'count'
        );
        $msgBackNum = GiftLog::checkSenderNum(
            $userId,
            $start,
            $end,
            [GiftLog::FROM_SUPER_CHAT, GiftLog::FROM_SYS_ONLINE],
            GiftLog::STATUS_OK
        );
        //成功
        $succCallNum = VideoCall::getCallNum('caller_num', $start, $end, CallBase::FROM_HOST_CALL, 0, $userId);
        //速配次数
        $matchNum = VideoCall::getCallNum('receiver_num', $start, $end, CallBase::FROM_DAILY_FREE_HOST, $userId);
        //收入
        $incomeFrom = [
            CoinLog::FROM_GET_GIFT,
            CoinLog::FROM_SEND_PRIVATE_MSG_IN,
            CoinLog::FROM_GET_SYSGIFT
        ];
        $incomeInfo = CoinLog::getTotalIncome([$userId], $start, $end, $incomeFrom, true);
        //视频接听时间
        $videoAnswerTime = VideoCall::getCallNum('total_call_minutes', $start, $end, 0, 0, $userId);
        //视频呼叫时间
        $videoCallTime = VideoCall::getCallNum('total_call_minutes', $start, $end, 0, $userId);
        //视频接听次数
        $succAnswerNum = VideoCall::getCallNum('success_num', $start, $end, 0, 0, $userId);
        //视频呼叫次数
        $succCallNum = VideoCall::getCallNum('success_num', $start, $end, 0, $userId);
        //总接听次数
        $answerNum = VideoCall::getCallNum('all', $start, $end, 0, 0, $userId);
        //总通话时长
        $totalCallMinutes = $videoAnswerTime + $videoCallTime;
        //总通话次数
        $totalCallNum = $succAnswerNum + $succCallNum;
        $info = [
            'income_total' => CoinLog::getTotalIncome([$userId], $start, $end),
            'income_gift' => $incomeInfo[CoinLog::FROM_GET_GIFT] ?? 0,
            'income_msg' => $incomeInfo[CoinLog::FROM_SEND_PRIVATE_MSG_IN] ?? 0,
            'income_sysgift' => $incomeInfo[CoinLog::FROM_GET_SYSGIFT] ?? 0,
            'income_voice' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::VOICE_CALL_INCOME),
            'income_video' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::VIDEO_CALL_INCOME),
            //视频接听时长（分钟）
            'video_answer_time' => $videoAnswerTime,
            //视频接听次数
            'video_answer_num' => $succAnswerNum,
            //视频呼叫次数
            'video_call_num' => $succCallNum,
            //主动速配次数
            'video_match_num' => $matchNum,
            //主动搭讪
            'super_chat_num' => UserChat::checkToday($userId, $start, $end),
            'success_rate' => !$answerNum ? 0 : (round($succAnswerNum / $answerNum, 3) * 100),
            'msg_back_rate' => !$senderNum ? 0 : (round($msgBackNum / $senderNum, 3) * 100),
            //名义礼物赠送人数
            'receive_user_num' =>  $senderNum,
            //名义礼物回复用户数
            'msg_back_num' => $msgBackNum,
            //名义礼物赠送个数
            'receive_num' => $sendGiftNum,
            //在线信息
            'online_time' => $onlineInfo[$userId] ?? 0,
            //平均通话时间
            'average_call_time' => !$totalCallNum ? 0 : ceil($totalCallMinutes * 60 / $totalCallNum),
            //通话时长
            'call_minutes' => $totalCallMinutes,
            'income_video_default' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_VIDEOCALL_IN),
            'income_video_match' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_QUICK_VIDEO_IN),
            'income_video_invite' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_INVITE_VIDEO),
            'income_video_discount' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_DISCOUNT_VIDEO_CALL_IN),
            'income_video_daily_free' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_DAILY_FREE),
            'income_daily_task' => CoinLog::getTotalIncome([$userId], $start, $end, CoinLog::FROM_DAILY_TASK),
        ];
        log_user_result($userId, $info);
        return StatDailyHostInfo::updateOrCreate(['user_id' => $userId, 'dt' => $start], $info);
    }
}
